﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using VirusCleaner.IPlugin.Host;
using VirusCleaner.IPlugin.Plugin;
using XPTable.Models;
using System.Reflection;
using VirusCleaner.IPlugin;
//=========================================
//
// 作 者：LsongStudio
// 邮 箱：song940@gmail.com
// 博 客：http://lsongs.host.sk/
// 时 间：2010-11-24 18:37:56
//
//=========================================
namespace VirusCleaner.Examine
{
    public partial class ExamineControl : UserControl,IUiElement,IExamineHost
    {
        private Thread _thread = null;
        private List<IExamine> _plugins;

        public ExamineControl()
        {
            InitializeComponent();
        }
        #region IPlugin 成员

        public string PluginName
        {
            get { return ""; }
        }

        #endregion

        #region IUiElement 成员

        public int Init()
        {
            LoadPlugins(@"Addins");
            this.examinePanel1.CancelButtonText = "";
            this.examinePanel1.Value = -1;
            this.examinePanel1.Maximum = 100;
            return 0;
        }

        public void Active(bool active)
        {
            tabControlMain.SelectTab(0);
        }

        #endregion

        #region IHost 成员


        public int LoadPlugins(string path)
        {
            _plugins = new List<IExamine>();
            foreach (string file in Directory.GetFiles(path, "*.dll"))
            {
                string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
                Assembly assmbly = Assembly.LoadFile(fileName);
                foreach (Type t in assmbly.GetTypes())
                {
                    if (t.IsClass == true && typeof(IExamine).IsAssignableFrom(t))
                    {
                        var plugin = Activator.CreateInstance(t) as IExamine;
                        _plugins.Add(plugin);
                    }
                }
            }
            return 0;
        }

        #endregion

        #region IExamineHost 成员

        public List<IExamine> Plugins
        {
            get { return _plugins; }
        }

        public IExamine GetPlugin(string name)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region 
        /// <summary>
        /// 安全体检
        /// </summary>
        private void SecurityExamine()
        {
            Invoke(new Action(Reset));
            //所有项目填充到列表
            foreach (IExamine plugin in _plugins)
            {
                Invoke(new Action<IExamine>(obj => tableModel1.Rows.Add(new Row(new[]
                                                                                          {
                                                                                              new Cell("0"),
                                                                                              new Cell(obj.PluginName),
                                                                                              new Cell("等待检测..")
                                                                                                  {Enabled = false}

                                                                                          }))), plugin);
            }
            //开始检测
            for (int i = 0; i < _plugins.Count; i++)
            {
                string text;
                IExamine plugin = _plugins[i];
                Invoke(new Action<int>(x =>
                                           {
                                               tableModel1.Rows[x].Cells[2].Text = @"正在检测...";
                                               int y = listViewScan.AutoScrollOffset.Y;
                                               listViewScan.AutoScrollOffset = new Point(0,y + 100);
                                           }), i);
                //
                int level = plugin.StartSign(out text, ChangeState);
                //
                Invoke(new Action<int>(obj =>
                                           {
                                               tableModel1.Rows[obj].Cells[0].Text = level.ToString();
                                               tableModel1.Rows[obj].Cells[0].Image = imageListState.Images[level];
                                               tableModel1.Rows[obj].Cells[2].Text = text;
                                               if (level != 0)
                                               {
                                                   tableModel1.Rows[obj].ForeColor = Color.Red;
                                               }
                                           }), i);
            }
            //over
            Invoke(new Action(Over));
        }
        void Over()
        {
            examinePanel1.Value = -1;
            examinePanel1.Text = @"您的电脑状态良好.";
            examinePanel1.CancelButtonText = "";
            examinePanel1.ReScanButtonText = "重新扫描.";

            var rows = new List<Row>(tableModel1.Rows.Count);
            //安全
            Row r1 = new Row(new[] {"", "安全的项目-(0)"}) {ForeColor = Color.Green, Font = new Font("微软雅黑", 9)};
            //优化
            Row r2 = new Row(new[] {"", "优化的项目-(0)"}) {ForeColor = Color.Blue, Font = new Font("微软雅黑", 10)};
            //警告
            Row r3 = new Row(new[] {"", "警告的项目-(0)"}) {ForeColor = Color.Gold, Font = new Font("微软雅黑", 11)};
            //威胁
            Row r4 = new Row(new[] {"", "威胁的项目-(0)"}) {ForeColor = Color.Red, Font = new Font("微软雅黑", 12)};

            for (int index = 3; index >= 0; index--)
            {
                int count = 0;
                foreach (Row r in tableModel1.Rows)
                {
                    r.Cells[0].Enabled = false;
                    r.Cells[1].Enabled = false;
                    int level = Int32.Parse(r.Cells[0].Text);
                    r.Cells[2].Enabled = level > 0;
                    if (index == level)
                    {
                        switch (level)
                        {
                            case 0:
                                if (!rows.Contains(r1))
                                {
                                    rows.Add(r1);
                                }
                                rows.Add(r);
                                count++;
                                r1.Cells[1].Text = String.Format("安全的项目-({0})", count);
                                break;
                            case 1:
                                if (!rows.Contains(r2))
                                {
                                    rows.Add(r2);
                                }
                                rows.Add(r);
                                count++;
                                r2.Cells[1].Text = String.Format("优化的项目-({0})", count);
                                break;
                            case 2:
                                if (!rows.Contains(r3))
                                {
                                    rows.Add(r3);
                                }
                                rows.Add(r);
                                count++;
                                r3.Cells[1].Text = String.Format("警告的项目-({0})", count);
                                break;
                            case 3:
                                if (!rows.Contains(r4))
                                {
                                    rows.Add(r4);
                                }
                                rows.Add(r);
                                count++;
                                r4.Cells[1].Text = String.Format("威胁的项目-({0})", count);
                                break;
                        }
                    }
                    
                }
            }
            tableModel1.Rows.Clear();
            tableModel1.Rows.AddRange(rows.ToArray());
        }

        private void ChangeState(string text, int value,int scroce)
        {
            examinePanel1.ScoreText = ( value).ToString();
            examinePanel1.StateText = text;
        }
        private void Reset()
        {
            if (_plugins == null)
            {
                MessageBox.Show(@"Null");
                _thread.Abort();
                return;
            }
            //初始化
            tabControlMain.SelectTab(1);
            tableModel1.Rows.Clear();
            //重置 组件
            examinePanel1.Value = 0;
            examinePanel1.ReScanButtonText = "";
            examinePanel1.CancelButtonText = "取消扫描";
            //
        }

        private void BtnCancelClick(object sender, EventArgs e)
        {
            _thread.Abort();
            examinePanel1.Value = -1;
            examinePanel1.CancelButtonText = "";
            examinePanel1.Text = @"体检被取消,建议重新扫描.";
            examinePanel1.ReScanButtonText = "重新扫描";
        }
        private void BtnReScanClick(object sender, EventArgs e)
        {
            BtnScanClick(sender, e);
        }
        private void LnkScanSettingLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (new ExamineSetting().ShowDialog(this) == DialogResult.OK)
            {

            }
        }
        private void ListViewScanSizeChanged(object sender, EventArgs e)
        {
            int wid = imageColumn1.Width + buttonColumn2.Width;
            textColumn1.Width = listViewScan.Width - wid - 50;
        }

        private void ListViewScanCellButtonClicked(object sender, XPTable.Events.CellButtonEventArgs e)
        {
            if (_plugins.Count > e.Cell.Row.Index)
                _plugins[e.Cell.Row.Index].Repair((x, y,z) =>
                {
                    lblTips.Text = x;
                    examinePanel1.Value += y;
                });
        }
        private void BtnScanClick(object sender, EventArgs e)
        {
            _thread = new Thread(SecurityExamine);
            _thread.Start();
        }
        #endregion
    }
}
